<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#example').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>
<?php

function chk_folder($filename)
{ //echo $filename;
	$fp_load = @fopen($filename, "rb");
	if ( $fp_load )
	{ 
		return true;
	}
	else
	{ 
		return false;
	}
}

function getDistanceFromDB($distDate,$devImei)
{
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

	$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$_SESSION[clientID]." AND tmsi_imei = '".$devImei."' AND tmsi_readDate = '".date('Y-m-d',strtotime($distDate))."'";
	$resDateReading = $db->query($getDateReading);
	if($db->affected_rows == 0)
	{		
		return -1;
	}
	else
	{
		$fetDateReading = $db->fetch_array($resDateReading);
		
		return $fetDateReading[tmsi_kmpd]."#".$fetDateReading[tmsi_startPoint]."#".$fetDateReading[tmsi_endPoint];
	}
	
}
function instertDistanceToDB($distDate,$devImei,$dist,$spt,$ept)
{
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

	$getDateReading = "SELECT * FROM tb_speed_meter_info WHERE tmsi_clientId = ".$_SESSION[clientID]." AND tmsi_imei = '".$devImei."' AND tmsi_readDate = '".date('Y-m-d',strtotime($distDate))."'";
	$resDateReading = $db->query($getDateReading);
	$diffTime = floatval(strtotime(date("d-m-Y")) - strtotime(date("d-m-Y",strtotime($distDate))));
	
	if($db->affected_rows == 0 && $diffTime !=0)
	{		
		$kmdata['tmsi_clientId'] = $_SESSION[clientID];
		$kmdata['tmsi_imei'] = $devImei;
		$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($distDate));
		$kmdata['tmsi_kmpd'] = $dist;
		$kmdata['tmsi_startPoint'] = $spt;
		$kmdata['tmsi_endPoint'] = $ept;
		
		//echo "<pre>";
//		print_r($kmdata);
		//echo "</pre>";
		//exit;
		$db->query_insert("tb_speed_meter_info", $kmdata);
	}
	/*else
	{
		$fetDateReading = $db->fetch_array($resDateReading);
		
		$kmdata['tmsi_clientId'] = $_SESSION[clientID];
		$kmdata['tmsi_imei'] = $devImei;
		$kmdata['tmsi_readDate'] = date('Y-m-d',strtotime($distDate));
		if($fetDateReading[tmsi_kmpd] == "" || $fetDateReading[tmsi_kmpd] < $dis || $fetDateReading[tmsi_kmpd] == $dis)
			$kmdata['tmsi_kmpd'] = $dist;
		
		$db->query_update("tb_speed_meter_info", $kmdata, "tsmi_id = ".$fetDateReading[tsmi_id]);
	}*/
	
}
function gpspathFunAll($date_offline,$deviceIMEI)
{
	$path1=DATAPATH.date('d-m-Y',strtotime($date_offline))."/".$deviceIMEI.".txt";
	
	if(chk_folder($path1))
	{
		$file1 = @fopen($path1, "r");
		if($file1)
		{
			$i=0;
			while(!feof($file1))
			{
			  $data1= fgets($file1);				 
			}
			$data1 = getSortedData($data1);
			fclose($file1);
		}
		return $data1;
	}
		
}
function liveKmsPerDay($lData,$sTime1,$eTime1)
{ 
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); 
$db->connect(); 

	$timeArr = array();
	//$ptArr = array();
	$cnt = 0;
	$totalDistance = 0;
	$data1=explode("#",$lData);
	for($j1=0;$j1<count($data1);$j1++)
	{
		$data2=explode("@",$data1[$j1]);

		if(count($data2)>1)
		{
			$data3=explode(",",$data2[1]);
			
			$geodate = $data3[8];
			$geoTime = $data3[9];
			$curTime = explode(":",$data3[9]);
			$curTime = (($curTime[0] * 60) + $curTime[1]);
			//echo "<br>";
			
			if($curTime >= $sTime1 && $curTime<=$eTime1)
			{
			
			$pos1=calLat($data3[2]);
			$pos2=calLong($data3[1]);
			
			if($pos1>0 && $pos2>0)
			{				
				if(!in_array($geoTime,$timeArr))
				{
					if($cnt==0)
					{
						$pits1 =  $pos1;
						$pits2 =  $pos2;
						$startPt = getHomeGeoAddress($pos1,$pos2)."#".$pos1."#".$pos2;
					}
					else
					{
						$pits3 =  $pos1;
						$pits4 =  $pos2;
						//echo $sTime1." >= ".$curTime." <= ".$eTime1." ".$totalDistance."<br>";
						$dist = getDistance($pits1, $pits2, $pits3, $pits4);
						if($dist <= 10)
						{
							$totalDistance += $dist;
						}
						
						$pits1 =  $pits3;
						$pits2 =  $pits4;
					}
					$cnt++;
				}
			}
				
			}
		}
		array_push($timeArr,$geoTime);
	}
	$endPt = getHomeGeoAddress($pos1,$pos2)."#".$pos1."#".$pos2;
	//if(strtotime(date("d-m-Y")) != strtotime(date("d-m-Y",strtotime($geodate))))
	//{		
		instertDistanceToDB($geodate,$data3[0],round($totalDistance,4),$startPt,$endPt);
	/*}
	elseif(strtotime(date("d-m-Y")) == strtotime(date("d-m-Y",strtotime($geodate))))
	{
		$getLiveData = "SELECT * FROM tb_livegps_info WHERE tli_imei = '".$data3[0]."'";
		$exeLiveData = $db->query($getLiveData);
		if($db->affected_rows > 0)
		{
			$fetLiveData = $db->fetch_array($exeLiveData);
			
			$lastData1=explode("#",$fetLiveData[tli_parameter]);
			$lastData2=explode("@",$lastData1[count($lastData1)-2]);
			if(count($lastData2)>1)
			{
				$lastData3=explode(",",$lastData2[1]);
				
				$lastDist = getDistance(calLat($lastData3[2]), calLong($lastData3[1]), $pos1, $pos12);
				
				$livedata["tli_imei"] = $data3[0];
				$livedata["tli_parameter"] = "@".implode(",",$data3)."#";
				$livedata["tli_distance"] = round($totalDistance,4);
				$livedata["tli_date"] = $data3[8];
				$livedata["tli_time"] = $data3[9];
				$livedata["tli_updateTime"] = 'NOW()';
				//print_r($livedata);exit;
				$db->query_update("tb_livegps_info", $livedata, "tli_imei = ".$data3[0]);
			}
		}
		else
		{
			$livedata["tli_imei"] = $data3[0];
			$livedata["tli_parameter"] = "@".implode(",",$data3)."#";
			$livedata["tli_distance"] = round($totalDistance,4);
			$livedata["tli_date"] = $data3[8];
			$livedata["tli_time"] = $data3[9];
			$livedata["tli_updateTime"] = 'NOW()';
			//print_r($livedata);exit;
			$db->query_insert("tb_livegps_info", $livedata);
		}
	}*/
	//$res=simpleGeocode($pos1,$pos2);
	//$res=str_replace('"',"",$res);
	$finalData = round($totalDistance,4);
	return $finalData."#".$startPt."#".$endPt;
}

if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	


?>
<script type="text/javascript" language="javascript">


function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  { alert("Select Vehicle");  document.getElementById('map_device_id').focus();  return 0;  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
	 var t1=document.getElementById('from_date').value ;
     var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }
	
	return 1;
	
}
function sendCSVData()
{
  document.frmKiloData.submit();
}
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}


function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{

		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';

}

$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();"> 
<table class="gridform_final">
<tr><th colspan="7">Distance Report</th></tr>
  <tr>
    <td width="10%" align="right"><span class="form_text">Select Device</span></td>
    <td width="20%" align="left">
        <select name="map_device_id" id="map_device_id" class="hours_select" tabindex="1" style="width:100%;" onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text">
        <option value="0">Select Device</option>
        <?php 
        while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
        {
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } }?>	
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td width="8%" align="right"><span class="form_text">From Date</span></td>
    <td width="17%" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" tabindex="2" size="12" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/>
    </td>
    <td width="8%" align="right"><span class="form_text">To Date</span></td>
    <td width="17%">
    <input type="text" name="to_date" id="to_date" size="12" style="width:140px;" tabindex="4" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />
    </td>
    <td width="35%" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=distance';" tabindex="7" /> 
</td>
  </tr>
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>	
	
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{ 
//print_r($_POST);
?>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">   
<thead>
      <tr>
	  	<th width="5%">#</th>
        <th width="7%">Date </th>
        <th width="12%">Device Name</th>
		<th width="32%">Start Location</th>
		<th width="32%">End Location</th>
        <th width="20%" >Kilometer (km)</th>
       </tr>
</thead>
<tbody>
<?php
	$sdate = $_POST[from_date];
	$edate = $_POST[to_date];

	$strtTime = 0;
	$endTime = 1439;
	
	if($_POST[from_date] == $_POST[to_date])
	{
		$dbDist = getDistanceFromDB($_POST[from_date],$_POST[map_device_id]);
		if($dbDist == -1)
		{
			$data =  gpspathFunAll($_POST[from_date],$_POST[map_device_id]);
			$dbDist = liveKmsPerDay($data,$strtTime,$endTime);
		}
		$finData =  $_POST[from_date]."#".$dbDist;
	}
	else
	{
		$z = GetDays($sdate, $edate);
		for($y=0; $y<count($z); $y++)
		{ 
			if($y == 0) 
			{				
				$dbDist1 = getDistanceFromDB($z[$y],$_POST[map_device_id]);
				if($dbDist1 == -1)
				{
					$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);
					$dbDist1 = liveKmsPerDay($data,$strtTime,$endTime);
				}
				$finData[] =  $z[$y]."#".$dbDist1;
			}
			elseif($y == count($z)-1) 
			{
				$dbDist2 = getDistanceFromDB($z[$y],$_POST[map_device_id]);
				if($dbDist2 == -1)
				{
					$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);
					$dbDist2 = liveKmsPerDay($data,$strtTime,$endTime);
				}
				$finData[] =  $z[$y]."#".$dbDist2;
			}
			elseif($y < count($z)-1) 
			{
				$dbDist3 = getDistanceFromDB($z[$y],$_POST[map_device_id]);
				if($dbDist3 == -1)
				{
					$data =  gpspathFunAll($z[$y],$_POST[map_device_id]);
					$dbDist3 = liveKmsPerDay($data,$strtTime,$endTime);
				}
				$finData[] =  $z[$y]."#".$dbDist3;
			}
		}
		$finData = implode("@",$finData);
	}
	//print_r($finData);
 	$cont = 0;
	if(count($finData)>0)
	{
		$finData = explode("@",$finData);
	for($x=0; $x<count($finData); $x++)
	{
	 	$splitData = explode("#",$finData[$x]);
		if($splitData[1] > 0){
		$totKm += round($splitData[1],2);
		//print_r($splitData);		
		if(!$splitData[2])
		{
			$strAddr = getGeocodePOI($splitData[3].','.$splitData[4]);
		}
		else 
			$strAddr = $splitData[2];
			
		if(!$splitData[5])
		{
			$endAddr = getGeocodePOI($splitData[6].','.$splitData[7]);
		}
		else 
			$endAddr = $splitData[5];
		
		/*$strAddr1 = getMyGeoAddress($splitData[2]);	
		if($strAddr1 == '')
			$strAddr = $splitData[2];
		else $strAddr = $strAddr1;
			
		$endAddr1 = getMyGeoAddress($splitData[3]);	
		if($endAddr1 == '')
			$endAddr = $splitData[3];
		else
			$endAddr = $endAddr1;*/
		
    
?>	  
      <tr <?php if($cont % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
	    <td><?php echo $cont+1;?></td>
		<td><?php echo date("d-m-Y",strtotime($splitData[0])); ?></td>
        <td><?php echo ucfirst($_POST[txtVehicleName]);?></td>
		<td><?php echo ucfirst($strAddr);?></td>
		<td><?php echo ucfirst($endAddr);?></td>
		<td><?php echo round($splitData[1],2); ?></td>
      </tr>
<?php      
	   $cont++; 
	   $strAddr1 = '';
	   $endAddr1 = '';
	   }
   }
} ///end of if(file exists)
?>	  
	 <tfoot>
		<tr>
			<td align="right" colspan="5">Total Km Travelled in <?php echo $cont; ?> day(s)</td>
			<td><?php echo $totKm; ?></td>
		</tr>
	</tfoot>
</table>	
 </tbody>
</table>
<?php
  
}///end of post

?>

